#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <string>
#include <errno.h>

void SetNonBlock(int fd)
{
    int n = ::fcntl(fd,F_GETFL);
    if(n < 0)
    {
        perror("fcntl");
        return ;
    }
    fcntl(fd,F_SETFL,n | O_NONBLOCK);
}
int main()
{
    std::string message = "Please Enter# ";
    SetNonBlock(0);
    char buffer[1024];
    while(true)
    {
        write(0,message.c_str(),message.size());
        int n = read(0,buffer,sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
        else if(n == 0)
        {
            std::cout << "read file end" << std::endl;
        }
        else
        {
            // EAGAIN		11	/* Try again */
            // EWOULDBLOCK	EAGAIN	/* Operation would block */
            if(errno == EAGAIN || errno == EWOULDBLOCK)
            {
                std::cout << "底层数据，没有就绪" << std::endl;
                sleep(1);

                continue;
            }
            else if (errno == EINTR)
            {
                std::cout << "被中断,从新来" << std::endl;
                sleep(1);

                continue;
            }
            else
            {
                std::cout << "read error: " << n << ", errno: " << errno << std::endl;
            }
        }
    }
    return 0;
}